package com.rule;

import com.netflix.client.config.IClientConfig;
import com.netflix.loadbalancer.AbstractLoadBalancerRule;
import com.netflix.loadbalancer.ILoadBalancer;
import com.netflix.loadbalancer.Server;
import java.util.List;

/**
 * @author chenyuan
 * @date 2020/9/30 12:31
 */
public class DiyRule extends AbstractLoadBalancerRule {

    public Server choose(ILoadBalancer lb, Object key) {
        if (lb == null) {
            return null;
        } else {
            Server server = null;

            while(server == null) {
                if (Thread.interrupted()) {
                    return null;
                }
                // 获得可获得（活着的）的服务
                List<Server> upList = lb.getReachableServers();
                // 获得所有的服务
                List<Server> allList = lb.getAllServers();
                int serverCount = allList.size();
                if (serverCount == 0) {
                    return null;
                }

            //==上面是写死的======中间是修改部分==================
                System.out.println("自定义的 Rule");
                System.out.println(upList.size());
                // 访问某一个提供者的次数
                int times = 0;
                // 提供者的下标
                int index = 0;
                // 从活着的服务中随机获取一个
                server = (Server)upList.get(index);
                if (times < 5){
                    times++;
                }else {
                    times = 1;
                    index = (index + 1) % upList.size();
                }

            //==下面是写死的======中间是修改部分===================

                if (server == null) {
                    Thread.yield();
                } else {
                    if (server.isAlive()) {
                        return server;
                    }

                    server = null;
                    Thread.yield();
                }
            }

            return server;
        }
    }

    @Override
    public void initWithNiwsConfig(IClientConfig iClientConfig) {

    }

    @Override
    public Server choose(Object o) {
        return null;
    }
}
